package com.atom.app.mvi.ui.main

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import com.atom.app.mvi.R
import com.atom.app.mvi.databinding.ActivityMainBinding
import com.atom.app.mvi.ui.main.f1.Feature1
import com.atom.app.mvi.ui.main.f2.Feature2
import com.atom.app.mvi.ui.rd.LoginActivity
import com.atom.module.logger.Logger
import com.atom.module.mvi.android.lifecycle.CreateDestroyBinderLifecycle
import com.atom.module.mvi.android.lifecycle.ResumePauseBinderLifecycle
import com.atom.module.mvi.android.lifecycle.StartStopBinderLifecycle
import com.atom.module.mvi.android.lifecycle.createDestroy
import com.atom.module.mvi.android.view.MVIActivity
import com.atom.module.mvi.binder.Binder
import com.atom.module.mvi.binder.named
import com.atom.module.mvi.binder.using
import com.atom.module.mvi.util.Result2
import com.atom.module.mvi.util.combineLatest
import com.squareup.picasso.Picasso
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.subjects.PublishSubject

data class ViewModel(
    val buttonColors: List<Int>,
    val counter: Int,
    val imageUrl: String?,
    val imageIsLoading: Boolean
)

sealed class UiEvent {
    data class ButtonClicked(val idx: Int) : UiEvent()
    object PlusClicked : UiEvent()
    object ImageClicked : UiEvent()
}

class ViewModelTransformer : (Result2<Feature1.State, Feature2.State>) -> ViewModel {

    override fun invoke(pair: Result2<Feature1.State, Feature2.State>): ViewModel {
        val (state1, state2) = pair

        return ViewModel(
            buttonColors = colors(state1.activeButtonIdx),
            counter = state1.counter,
            imageIsLoading = state2.isLoading,
            imageUrl = state2.imageUrl
        )
    }

    private fun colors(active: Int?): List<Int> = listOf(
        if (active == 0) R.color.pink_800 else R.color.pink_500,
        if (active == 1) R.color.light_blue_800 else R.color.light_blue_500,
        if (active == 2) R.color.lime_800 else R.color.lime_500,
        if (active == 3) R.color.yellow_800 else R.color.yellow_500
    )
}

class MainActivity : MVIActivity<UiEvent, ViewModel>() {

    private lateinit var buttons: List<View>
    private lateinit var binding: ActivityMainBinding

    private val events = PublishSubject.create<String>()
    private val dummyConsumer = Consumer<String> {
        Logger.tag("MainActivity").e(it)
    }

    override fun binder(): Binder {
        return this.lifecycle.createDestroy {
            val feature1 = Feature1()
            val feature2 = Feature2()
            val analyticsTracker = FakeAnalyticsTracker(this@MainActivity)
            val newsListener = NewsListener(this@MainActivity)
            this.bind(
                combineLatest(
                    feature1, feature2
                ) to this@MainActivity using ViewModelTransformer() named "MainActivity.ViewModels"
            )
            this.bind(this@MainActivity to feature1 named "MainActivity.feature1")
            this.bind(this@MainActivity to feature2 named "MainActivity.feature2")

            this.bind(this@MainActivity to analyticsTracker named "MainActivity.Analytics")
            this.bind(feature2.news to newsListener named "MainActivity.News")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        buttons = listOf(binding.button0, binding.button1, binding.button2, binding.button3)
        buttons.forEachIndexed { idx, button ->
            button.setOnClickListener {
                onNext(
                    UiEvent.ButtonClicked(
                        idx
                    )
                )
            }
        }
        binding.image.setOnClickListener { onNext(UiEvent.ImageClicked) }
        binding.fab.setOnClickListener { onNext(UiEvent.PlusClicked) }
        binding.signOut.setOnClickListener {

        }
        binding.showToasts.setOnClickListener {
            // Only for debugging purposes, otherwise should be part of the state!

        }

        binding.help.setOnClickListener {

        }

        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
//        binding.navigationView.init(binding.drawerLayout, 0)

        Binder(CreateDestroyBinderLifecycle(lifecycle))
            .bind(events to dummyConsumer named "Lifecycle#CreateDestroy")

        Binder(StartStopBinderLifecycle(lifecycle))
            .bind(events to dummyConsumer named "Lifecycle#StartStop")

        Binder(ResumePauseBinderLifecycle(lifecycle))
            .bind(events to dummyConsumer named "Lifecycle#ResumePause")

        events.onNext("onCreate")

    }
    override fun accept(vm: ViewModel) {
        binding.counter.text = vm.counter.toString()
        buttons.forEachIndexed { idx, button -> button.setBackgroundColor(resources.getColor(vm.buttonColors[idx]))}
        binding.imageProgress.visibility = if (vm.imageIsLoading) View.VISIBLE else View.GONE
        Picasso.get().load(vm.imageUrl).into(binding.image)
    }



    override fun onStart() {
        super.onStart()

        events.onNext("onStart")
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)

        events.onNext("onRestoreState")
    }

    override fun onResume() {
        super.onResume()

        events.onNext("onResume")
    }

    override fun onPostResume() {
        super.onPostResume()

        events.onNext("onPostResume")
    }

    override fun onPause() {
        super.onPause()

        events.onNext("onPause")
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)

        events.onNext("onSaveState")
    }

    override fun onStop() {
        super.onStop()

        events.onNext("onStop")
    }

    override fun onDestroy() {
        super.onDestroy()

        events.onNext("onDestroy")
    }

}